package com.example.lottery_system.service.impl;

import com.example.lottery_system.common.errorcode.ServiceConstants;
import com.example.lottery_system.common.exception.ServiceException;
import com.example.lottery_system.common.utils.*;
import com.example.lottery_system.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private final static String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_475280237";
    private final static String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private final static Long VERIFICATION_CODE_TIMEOUT = 60L;


    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCodeService(String phoneNumber) {
        // 手机号校验
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceConstants.PHONE_NUMBER_ERROR);
        }

        // 生成随机验证码
        String code = CapitalUtil.getCapital(4);

        // 发送验证码
        /**
         * smsUtil.sendMessage(
         *                 "SMS_475280237",
         *                 "19583716513",
         *                 "{\"code\":\"1234\"}" );
         *         // {"code":"1234"} // 引号需要转义
         */
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        smsUtil.sendMessage(
                VERIFICATION_CODE_TEMPLATE_CODE,
                phoneNumber,
                JacksonUtil.writeValueAsString(map));

        // 缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber, code, VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCodeService(String phoneNumber) {
        // 手机号校验
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceConstants.PHONE_NUMBER_ERROR);
        }

        // 获取验证码
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
